package server.main.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import server.business.pojo.ProcessEntity;
import server.business.service.ProcessService;

import server.main.mapper.FunctionPageMapper;
import server.main.mapper.PermissionMapper;
import server.main.pojo.ConfigBean;
import server.main.pojo.Permission;
import server.main.service.FunctionAddSevice;
import server.main.utils.mainutils.*;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("FunctionAddSevice")

public class FunctionAddServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements FunctionAddSevice {
    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    ProcessService processService;

    @Autowired
    FunctionPageMapper functionPageMapper;

    @Override
    public boolean addfunc(String filename) {
        //根据文件名解压
//        String mainpath = UrlUtils.GetMainUrl();
        String mainpath = UrlUtils.get_user_dir();
        String sourcepath = mainpath + "/temp/zip/";//网页上传下来之后压缩包存的文件夹
        String goalpath = mainpath + "/temp/temp/";//解压文件临时地址
        String delpath = mainpath + "/temp/temp";

        File tempdir = new File(delpath);


        try {
            if (!tempdir.exists()) {//如果文件夹不存在
                tempdir.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            FileUtils.unZipFiles(sourcepath + filename, goalpath);//解压
        } catch (IOException e) {
            e.printStackTrace();
        }

        String backendpath = UrlUtils.GetComUrl();//后端文件的地址
        String staticsourcepath = UrlUtils.GetResourcesUrl() + "static/";//static中的文件的地址
        String templatesourcepath = UrlUtils.GetResourcesUrl() + "template/";//模板文件的地址
        String mapperlatesourcepath = UrlUtils.GetResourcesUrl() + "mapper/";//mapper文件的地址

        //文件复制到相应的地方
        try {
            FileUtils.CopyDir(goalpath + "function/", backendpath);
            FileUtils.CopyDir(goalpath + "static/", staticsourcepath);
            FileUtils.CopyDir(goalpath + "template", templatesourcepath);
            FileUtils.CopyDir(goalpath + "mapper/", mapperlatesourcepath);

            System.out.println("文件转移完毕。");
        } catch (IOException e) {
            e.printStackTrace();
        }


        //解析config文件
        String configpath = goalpath + "config.json";//json文件的路径
        ConfigBean configBean = JsonUtils.GetConfigBean(configpath);//获得Json对象
        System.out.println("json解析完毕");

        //创建表
        try {
            createtable(configBean);
            System.out.println("表创建完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //更改pom.xml文件的相关依赖项
        try {
            changeMoven(configBean);
            System.out.println("pom.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //将process写入数据库
//        setProcess(configBean);

        //将添加的功能写入数据库中
        setfunction(configBean);
        System.out.println("function添加到数据库完毕");

        //temp中的解压的文件删除掉
        try {
            FileUtils.delFolder(delpath);
            System.out.println("文件删除完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }


        try {
            mvn(UrlUtils.GetMvnPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据config.json文件更改整体的config.txt文件
        changeConfigTxt("confi.txt", configBean);
        System.out.println("changeconfig success");
        //获取到config中的版本信息
        //地址信息
        Map<String, String> versionconfig = JsonUtils.GetTxtparam("confi.txt");
        String version = versionconfig.get("version");
        moveAndRenamejar(UrlUtils.GetJar(), mainpath + "/BloodTransfusionManagement-" + version + ".jar");
        System.out.println("rename file success");

        //重启工程
        AllCharge.restart();

        return true;
    }

    /**
     * 重新打包
     *
     * @param path 园项目路径
     * @return
     */


    public boolean mvn(String path) {
        //可以在文件的配置文件中新增要执行的mvn操作，现阶段就直接执行clean和package操作\
        maven.clean();
        maven.repackage();
        //        maven.maven_pck(path, "mvn clean", "mvn package");

        return true;

    }

    public boolean changeConfigTxt(String configpath, ConfigBean configBean) {
        ConfigBean.Config newconfig = configBean.getConfig();
        Map<String, String> configmap = JsonUtils.GetTxtparam(configpath);
        configmap.put("version", newconfig.getVersion());
        String goalstr = "";
        for (String key : configmap.keySet()) {
            goalstr += key + "=" + configmap.get(key) + "\n";
        }
        try {
            File file = new File(configpath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fileWriter = new FileWriter(file.getName(), false);
            fileWriter.write(goalstr);
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public boolean moveAndRenamejar(String sourcefile, String targetpath) {

        //命名格式为：BloodTransfusionManagement_版本号
        try {
            FileUtils.CopyFile(sourcefile, targetpath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 创建数据库中所需要的表
     *
     * @param configBean config解析出来的对象
     * @return
     */
    public boolean createtable(ConfigBean configBean) {
        /**
         *
         * @param table_name 所要建立的表的名字
         * @param key 是整个的表的属性
         * @param data_type 数据类型
         * @param data_length 数据长度
         * @param primarykey 主键
         * @param not_null 是否能为空，1为不为空，0为空。
         * @param auto_increase   是否自增，0非自增，1自增
         * @return 返回的是sql语句
         */


        for (ConfigBean.TableBean tableBean : configBean.getTable()) {
            String table_name, table_type;
            List<String> data_type = new ArrayList<String>();
            List<String> key_name = new ArrayList<String>();
            List<String> data_length = new ArrayList<String>();
            List<String> primarykey = new ArrayList<String>();
            List<Integer> not_null = new ArrayList<Integer>();
            List<Integer> auto_increase = new ArrayList<Integer>();
            table_name = tableBean.getTablename();
            table_type = tableBean.getTable_type();
            for (ConfigBean.TableBean.KeyBean keyBean : tableBean.getKey()) {
                key_name.add(keyBean.getName());
                data_type.add(keyBean.getData_type());
                data_length.add(keyBean.getLength());
                if (keyBean.getIf_mainkey().equals("1")) {
                    primarykey.add(keyBean.getName());
                }
                if (keyBean.getIf_increase().equals("1")) {
                    auto_increase.add(1);
                } else {
                    auto_increase.add(0);
                }
                if (keyBean.getIf_null().equals("1")) {
                    not_null.add(0);
                } else {
                    not_null.add(1);
                }
            }
            //获得全部所需要的数据
            String[] data_Type = OtherUtils.StringArrayList2List((ArrayList<String>) data_type);
            String[] key_Name = OtherUtils.StringArrayList2List((ArrayList<String>) key_name);
            String[] data_Length = OtherUtils.StringArrayList2List((ArrayList<String>) data_length);
            String[] primaryKey = OtherUtils.StringArrayList2List((ArrayList<String>) primarykey);
            Integer[] not_Null = OtherUtils.IntegerArrayList2List((ArrayList<Integer>) not_null);
            Integer[] auto_Increase = OtherUtils.IntegerArrayList2List((ArrayList<Integer>) auto_increase);
            //获得所需要的sql
            String sql = CreateTableUtils.Get_sql(table_name, key_Name, data_Type, data_Length, primaryKey, not_Null, auto_Increase);
            System.out.println(sql);
            //创建表
            try {
                boolean flag = CreateTableUtils.creat_table(sql);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        return false;
    }

    /**
     * 更行表中的信息
     *
     * @param configBean config解析出来的对象
     */
    public void setfunction(ConfigBean configBean) {
        String name, path, flag, description;
        for (ConfigBean.FunctionBean.BodyBean functionBean : configBean.getFunction().getBody()) {
            name = functionBean.getName();
            flag = functionBean.getFlag();
            path = functionBean.getFunction_url();
            description = functionBean.getDescription();
//            save(new Permission(null, name, path, description, flag));



        }

    }

    /**
     * 向pom.xml中添加依赖
     *
     * @param configBean config解析出来的对象
     */
    public void changeMoven(ConfigBean configBean) {
        String groupId, artifactId, version;
        String pomfilepath = UrlUtils.GetUrl() + "pom.xml";
        for (ConfigBean.DependenciesBean dependenciesBean : configBean.getDependencies()) {

            artifactId = dependenciesBean.getArtifactId();
            groupId = dependenciesBean.getGroupId();
            version = dependenciesBean.getVersion();
            System.out.println(groupId + " " + artifactId + " " + version);
            if ("null".equals(groupId) && "null".equals(artifactId)) {
                System.out.println("不添加");
            } else {
                try {
                    if ("null".equals(version)) {
                        ChangeXml.changemoven(pomfilepath, groupId, artifactId, null);
                    } else
                        ChangeXml.changemoven(pomfilepath, groupId, artifactId, version);

                    System.out.println("web.xml修改成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

    /**
     * 更新process中的数据
     *
     * @param configBean config解析出来的对象
     */
    public void setProcess(ConfigBean configBean) {
        for (ConfigBean.ProcessBean process : configBean.getProcess()) {

            processService.save(new ProcessEntity(null, process.getBussnessname(), process.getInputmsg(), process.getOutputmsg(), process.getClasspath(), process.getFrontpath(), process.getMethod()));


        }
    }


    public void test() {

        ConfigBean configBean = JsonUtils.GetConfigBean("config.json");//获得Json对象
        changeConfigTxt("confi.txt", configBean);

        Map<String, String> map = JsonUtils.GetTxtparam("confi.txt");
        System.out.println(map);


    }




}
